<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="fileName">
        <el-input
          v-model="queryParams.fileName"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="文件模块" prop="fileType">
          <el-select v-model="queryParams.fileType" placeholder="请选择内容"> 
            <el-option label="首页" value="首页"></el-option>
            <el-option label="多链钱包" value="多链钱包"></el-option> 
            <el-option label="硬件钱包" value="硬件钱包"></el-option> 
            <el-option label="公链" value="公链"></el-option> 
            <el-option label="公告" value="公告"></el-option> 
            <el-option label="帮助中心" value="帮助中心"></el-option> 
            <el-option label="立即下载" value="立即下载"></el-option> 
          </el-select>
      </el-form-item>
      <el-form-item label="ID标识" prop="filepathId">
        <el-input
          v-model="queryParams.filepathId"
          placeholder="请输入文件路径ID标识"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="地址" prop="path">
        <el-input
          v-model="queryParams.path"
          placeholder="请输入地址"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> 
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:file:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:file:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:file:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:file:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="fileList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" /> 
      <el-table-column label="文件模块" align="center" prop="fileType" />
      <el-table-column label="文件路径ID标识" align="center" prop="filepathId" />
      <el-table-column label="名称" align="center" prop="fileName" />
      <el-table-column label="地址" align="center" prop="path" />
      <el-table-column label="是否为外链" align="center" prop="isFrame" />
      <el-table-column label="备注" align="center" prop="remark" /> 
      
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:file:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:file:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改文件路径信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="fileName">
          <el-input v-model="form.fileName" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="翻译模块" prop="fileType">
          <el-select v-model="form.fileType" placeholder="请选择内容"> 
            <el-option label="首页" value="首页"></el-option>
            <el-option label="多链钱包" value="多链钱包"></el-option> 
            <el-option label="硬件钱包" value="硬件钱包"></el-option> 
            <el-option label="公链" value="公链"></el-option> 
            <el-option label="公告" value="公告"></el-option> 
            <el-option label="帮助中心" value="帮助中心"></el-option> 
            <el-option label="立即下载" value="立即下载"></el-option> 
          </el-select>
        </el-form-item>
        <el-form-item label="ID标识" prop="filepathId">
          <el-input v-model="form.filepathId" placeholder="请输入文件路径ID标识" />
        </el-form-item>
        <el-form-item label="项目图片" prop="pic">
          <el-upload
            ref="upload"
            action="#"
            :http-request="uploadFileceshi"
            :before-upload="beforeUploadceshi"
            :auto-upload="true"
            :limit="1"
            :on-exceed="handleExceedceshi"
            v-model="form.pic">
            <el-button size="small" type="primary">
              新增项目数据图片
              <i class="el-icon-upload el-icon--right"></i>
            </el-button>
            <template slot-scope="scope">
              <el-link>{{ scope.row.pic}}</el-link>
            </template>
          </el-upload>

          <el-button @click="handlePreviewceshi" title="预览图片">预览图片</el-button>
          <el-dialog title="图片预览" :visible.sync="previewDialogVisibleceshi" width="80%">
            <el-carousel   type="card"  :interval="5000">
              <el-carousel-item v-for="(item, index) in previewImageListceshi" :key="index">
                <el-image :src="item.src" style="height: 100%;" />
              </el-carousel-item>
            </el-carousel>
          </el-dialog>
        </el-form-item> 
        <el-form-item label="地址" prop="path">
          <el-input v-model="form.path" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="外链" prop="isFrame">
          <el-radio-group v-model="form.isFrame">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listFile, getFile, uploadAttachs,delFile, addFile, updateFile } from "@/api/supercells/file";
import axios from 'axios'
 
 
export default {
  name: "File",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 文件路径信息表格数据
      fileList: [],
      file: null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fileName: null,
        fileType: '首页',
        filepathId: null,
        path: null,
        isFrame: null,
      },
      previewImageListceshi:'',
      previewDialogVisibleceshi:false,
      attachFilesceshi: [],
      picfileList: [],
      // 表单参数
      form: {
        pic: ''
      },
      // 表单校验
      rules: {
        fileName: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询文件路径信息列表 */
    getList() {
      this.loading = true;
      listFile(this.queryParams).then(response => {
        this.fileList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    beforeUploadceshi(fileObj) {
        // const isJPG = fileObj.type === 'image/jpeg' || fileObj.type === 'image/png';
        // const isLt20M = fileObj.size / 1024 / 1024 < 20;
        //
        // if (!isJPG) {
        //     this.$message.error('上传附件只能是 JPG/PNG 格式!');
        //     return Promise.reject(false);
        // }
        // if (!isLt20M) {
        //     this.$message.error('上传附件大小不能超过 20MB!');
        //     return Promise.reject(false);
        // }
        // if (!this.attachFilesceshi) {
        //     this.attachFilesceshi = []; // 如果数组不存在，先创建
        // } 
        this.attachFilesceshi.push(fileObj);
        console.log(this.attachFilesceshi+" this.attachFilesceshi")
        return fileObj;
    }, 
    uploadFileceshi() {
        if (!this.attachFilesceshi || this.attachFilesceshi.length === 0) {
            this.message.warning("请选择文件!");
            return;
        }
        if ( this.attachFilesceshi.length > 1) {
            this.message.warning("只能选一个图片上传!");
            return;
        }
        let formData = new FormData();
        for (let i = 0; i < this.attachFilesceshi.length; i++) {
            formData.append("picture", this.attachFilesceshi[i]);
            continue;
        }
        console.log(formData); // 调试用，确认 formData 中包含多个键值对 
        uploadAttachs(formData).then((res) => { 
            console.log(`服务端返回数据：${res}`);
            let urls = res.split(","); // 将返回的字符串用逗号分隔开，得到多个 URL
            const lastUrlIndex = urls.length - 1; // 记录最后一个 URL 的下标
            let separator = ''; // 初始化一个分隔符 
            if (this.form.pic) { // 判断变量中是否已经有了 URL
                separator = ','; // 如果有，则将分隔符设置为逗号
            }
            for (let i = 0; i < urls.length; i++) {
                let url = urls[i].trim().replace('http://localhost:', 'http://192.168.100.141:'); // 去除 URL 中的空格
                this.form.pic = url; // 使用分隔符将 URL 拼接到变量中 
            }
            this.form.path = this.form.pic;
            console.log("this.form.pic" + this.form.pic);
            this.$message.success("附件上传成功!");
            // 清空表单数据及界面
            this.attachFilesceshi = []
        }).catch((error) => { 
            console.error(`附件上传失败：${error}`);
            this.$message.error("附件上传失败!");
            this.attachFilesceshi = []; // 清空数组
        });
    },
    //图片浏览方法,私用
    handlePreviewceshi() { 
        if (this.form.pic) {
            let urls = this.form.pic.split(",");
            console.log("urls"+"分割"+urls)
            if (urls.length > 0) {
                // 过滤掉不合法的 URL
                urls = urls.filter((url) => {
                    return url.trim().length > 0; // 过滤掉空白字符串或者不合法的 URL
                });
                // 初始化预览图片列表
                this.previewImageListceshi = [];
                urls.forEach((url) => {
                    this.previewImageListceshi.push({
                        src: url
                    });
                });
                // 打开图片预览弹窗
                this.previewDialogVisibleceshi = true;
            }
        }
    }, 
    //上传图片错误方法,公用
    handleExceedceshi(files, picfileList) {
        this.$message.warning(`当前限制选择 ${this.limit} 个文件，本次选择了 ${files.length} 个文件，已自动过滤多余的文件。`);
    }, 
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        fileId: null,
        fileName: null,
        fileType: null,
        filepathId: null,
        path: null,
        isFrame: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.fileId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加文件路径信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const fileId = row.fileId || this.ids
      getFile(fileId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改文件路径信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.fileId != null) {
            updateFile(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addFile(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const fileIds = row.fileId || this.ids;
      this.$modal.confirm('是否确认删除文件路径信息编号为"' + fileIds + '"的数据项？').then(function() {
        return delFile(fileIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/file/export', {
        ...this.queryParams
      }, `file_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
